const User = require('../modules/user');
const TeachMaterial = require('../modules/teachmaterial');
const AnswerLog = require('../modules/answerlog');

//返回数据格式
//{ msg: '', success: boolean, data: {} }
//注意ctx.success在条件分支语句中需要加return,不然继续往下执行

class UserController{

    static async homePage(ctx) {
        try {
            if(ctx.session.authorised !== true) return ctx.redirect('/login?msg=you need to log in')
            const data = {}
            if(ctx.query.msg) data.msg = ctx.query.msg;
            data.user=ctx.session.currentUser;
            let tm = await new TeachMaterial();
            data.teachMaterialList = await tm.listALl();
            // let  = await new User().getUserByName(data.user);
            let al = await new AnswerLog();
            data.answerLogList = await al.listAnswerLogByUserId(ctx.session.currentUserId);
            await ctx.render('index', data)
        } catch(err) {
            await ctx.render('error', {message: err.message})
        }
    }

    static async registerPage(ctx) {
        await ctx.render('register')
    }

    static async register(ctx) {
        let user;
        try {
            // extract the data from the request
            const body = ctx.request.body
            // call the functions in the module
            user = await new User()
            await user.register(body.user, body.pass)
            // await user.uploadPicture(path, type)
            // redirect to the home page
            ctx.redirect(`/?msg=new user "${body.name}" added`)
        } catch(err) {
            await ctx.render('error', {message: err.message})
        } 
    }

    static async loginPage(ctx) {
	    const data = {}
	    if(ctx.query.msg) data.msg = ctx.query.msg
	    if(ctx.query.user) data.user = ctx.query.user
	    await ctx.render('login', data)
    }

    static async login(ctx) {
        let user;
        try {
            const body = ctx.request.body;
            user = await new User();
            let userId = await user.login(body.user, body.pass);
            ctx.session.authorised = true;
            ctx.session.currentUser = body.user;
            ctx.session.currentUserId = userId;
            return ctx.redirect('/?msg=you are now logged in...')
        } catch(err) {
            await ctx.render('error', {message: err.message})
        } 
    }
    
    static async logout(ctx){
        ctx.session.authorised = null
        ctx.session.currentUser = null
        ctx.session.currentUserId = null
        ctx.redirect('/?msg=you are now logged out')
    }
    
}

exports = module.exports = UserController;